<?php

namespace app\modules\search\controllers;

use app\modules\setting\models\UserPermissions;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\modules\search\models\SearchPatient;
use app\modules\search\models\SearchExcel;
use app\modules\search\models\SearchExcelPd;
use app\modules\search\models\SearchCheck;
use app\modules\search\models\SearchGene;
use app\modules\search\models\SearchVisit;
use app\modules\search\models\SearchSenior;
use app\modules\clinical\models\Patient;
use app\models\HsptLabel;
use app\modules\clinical\models\ExcelPd;
use yii\web\ForbiddenHttpException;

class SearchController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->redirect('/search/search/patient');
    }

    public function actionPatient()
    {
        $queryParams = Yii::$app->request->queryParams;
        $queryParams = $this->_change_query_param_based_on_permissions($queryParams, 'SearchPatient', 'patient_search');

        $searchModel = new SearchPatient();
        $dataProvider = $searchModel->search($queryParams);
 
        return $this->render('patient', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionExcel()
    {
        $type = Yii::$app->request->get('type', false);
        switch ($type) {
            case 'pd':$searchModel = new SearchExcelPd(); $searchModelName = 'SearchExcelPd'; break;
            
            default:$searchModel = new SearchExcel(); $searchModelName = 'SearchExcel'; break;
        }

        $queryParams = Yii::$app->request->queryParams;
        $queryParams = $this->_change_query_param_based_on_permissions($queryParams, $searchModelName, 'excel_search');

        $dataProvider = $searchModel->search($queryParams);

        return $this->render('excel'.($type ? '_'.$type : ''), [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'type' => $type,
        ]);
    }

    public function actionCheck()
    {
        $queryParams = Yii::$app->request->queryParams;
        $queryParams = $this->_change_query_param_based_on_permissions($queryParams, 'SearchCheck', 'check_search');

        $searchModel = new SearchCheck();
        $dataProvider = $searchModel->search($queryParams);
 
        return $this->render('check', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionGene()
    {
        $queryParams = Yii::$app->request->queryParams;
        $queryParams = $this->_change_query_param_based_on_permissions($queryParams, 'SearchGene', 'gene_search');

        $searchModel = new SearchGene();
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('gene', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionVisit()
    {
        $queryParams = Yii::$app->request->queryParams;
        $queryParams = $this->_change_query_param_based_on_permissions($queryParams, 'SearchVisit', 'visit_search');

        $searchModel = new SearchVisit();
        $dataProvider = $searchModel->search($queryParams);
 
        return $this->render('visit', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionSenior()
    {
        $queryParams = Yii::$app->request->queryParams;
        $queryParams = $this->_change_query_param_based_on_permissions($queryParams, 'SearchSenior', 'advanced_search');

        $searchModel = new SearchSenior();
        $dataProvider = $searchModel->search($queryParams);

        $labels = HsptLabel::getArray();
        $med_rel = SearchSenior::values();
        $age_rel = SearchSenior::values();
        $med_info = ExcelPd::getMedList('pd');
        foreach ($med_info as $r) {
            $result[$r['pk_id']] = $r['med_name'];
        }

        return $this->render('senior', [
            'med_info' => $result,
            'med_rel' => $med_rel,
            'age_rel' => $age_rel,
            'labels' => $labels,
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionCreatePatient()
    {
        $model = new Patient();
        $model->defaultValue();

        return $this->render('/search/create-patient', [
            'model' => $model,
        ]);
    }


    /**
     * @return \yii\web\Response
     * @throws \yii\web\ForbiddenHttpException
     * @author sally
     * @date   2020-05-10
     */
    public function actionEnter() {
        $permission_flags = $this->_get_permission_flags();

        $session = Yii::$app->session;
        $type = Yii::$app->request->get('type', 'patient');
        $id = Yii::$app->request->get('id', 0);

        if (!$session->isActive) {
            $session->open();
        }

        if (($patient = Patient::findOne($id)) !== NULL) {
            if (
                // full access
                (!empty($permission_flags['full_access']) && $permission_flags['full_access']) ||
                // user created the profile
                $patient->crt_name == Yii::$app->user->identity->username
            ) {
                $session->set('pt_id', $patient->pk_id);
                $session->set('pt_name', $patient->pt_name);
                $session->set('dna', $patient->dna_id);
            }
            else {
                throw new ForbiddenHttpException('没有权限访问');
            }
        } else {
            return $this->goback();
        }

        return $this->redirect('/clinical/'.$type.'/index');
    }


    /**
     * @author sally
     * @date   2020-05-10
     */
    private function _get_permission_flags()
    {
        $is_admin = false;
        $flags = [
            'patient_search' => false,
            'excel_search' => false,
            'check_search' => false,
            'gene_search' => false,
            'visit_search' => false,
            'advanced_search' => false,
            'search_all' => false,
            'export_patient_info' => false,
        ];
        $permissions = UserPermissions::getPermissions(Yii::$app->user->identity->getId());

        foreach ($permissions as $permission) {
            $flags[$permission['permission_name']] = true;

            if ($permission['permission_name'] == 'full_access') {
                $is_admin = true;
            }
        }

        if ($is_admin) {
            foreach ($flags as $key => $flag) {
                $flags[$key] = true;
            }
        }

        return $flags;
    }


    /**
     * @param $queryParams
     * @param $searchModalName
     * @param $permission_name
     *
     * @return mixed
     * @author sally
     * @date   2020-05-10
     */
    private function _change_query_param_based_on_permissions($queryParams, $searchModalName, $permission_name)
    {
        $permission_flags = $this->_get_permission_flags();

        if (empty($permission_flags[$permission_name])) {
            $queryParams[$searchModalName]['crt_name'] = 'access denied';
        }
        else if (empty($permission_flags['search_all']) || !$permission_flags['search_all']) {
            $queryParams[$searchModalName]['crt_name'] = Yii::$app->user->identity->username;
        }

        return $queryParams;
    }
}
